<template>
  <div class="pet-list-container">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="名称">
          <el-input v-model="searchForm.name" placeholder="请输入宠物名称"></el-input>
        </el-form-item>
        <el-form-item label="类别">
          <el-select v-model="searchForm.category" placeholder="请选择宠物类别">
            <el-option label="猫" value="猫"></el-option>
            <el-option label="狗" value="狗"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="领养状态">
          <el-select v-model="searchForm.adoptionStatus" placeholder="请选择领养状态">
            <el-option label="待领养" value="AVAILABLE"></el-option>
            <el-option label="已领养" value="ADOPTED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" icon="el-icon-plus" @click="$router.push('/pets/create')" v-if="isAdmin">添加宠物</el-button>
    </div>

    <!-- 宠物列表 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="pet in petList" :key="pet.id">
        <el-card class="pet-card" :body-style="{ padding: '0px' }">
          <div class="pet-image" @click="viewDetail(pet.id)">
            <el-image
              :src="getImageUrl(pet.imageUrl)"
              fit="cover"
              style="width: 100%; height: 200px;">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <div class="adoption-status" :class="pet.adoptionStatus.toLowerCase()">
              {{ pet.adoptionStatus === 'AVAILABLE' ? '待领养' : '已领养' }}
            </div>
          </div>
          <div class="pet-info">
            <h3 class="pet-name">{{ pet.name }}</h3>
            <div class="pet-meta">
              <span>{{ pet.category }} | {{ pet.breed }}</span>
              <span>{{ pet.age }}岁 | {{ pet.gender }}</span>
            </div>
            <div class="pet-actions">
              <el-button type="text" @click="viewDetail(pet.id)">查看详情</el-button>
              <template v-if="isAdmin">
                <el-button type="text" @click="handleEdit(pet.id)">编辑</el-button>
                <el-button type="text" class="danger" @click="handleDelete(pet)">删除</el-button>
              </template>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNum"
        :page-sizes="[12, 24, 36, 48]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getPetList, deletePet } from '@/api/pet'
import { mapState } from 'vuex'

export default {
  name: 'PetList',
  data() {
    return {
      searchForm: {
        name: '',
        category: '',
        adoptionStatus: ''
      },
      petList: [],
      page: {
        pageNum: 1,
        pageSize: 12
      },
      total: 0,
      loading: false
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    }),
    isAdmin() {
      return this.userInfo && this.userInfo.roles && this.userInfo.roles.includes('ADMIN')
    }
  },
  methods: {
    // 获取完整的图片URL
    getImageUrl(path) {
      if (!path) {
        return require('@/assets/default-pet.jpg');
      }
      
      // 服务器地址
      const serverUrl = 'http://localhost:8080'; // 后端API服务器地址
      
      // 如果路径已经是完整URL，直接返回
      if (path.startsWith('http://') || path.startsWith('https://')) {
        return path;
      }
      
      // 确保路径以 / 开头
      if (!path.startsWith('/')) {
        path = '/' + path;
      }
      
      // 构建完整URL
      return serverUrl + path;
    },
    // 获取宠物列表
    async fetchPetList() {
      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          pageNum: this.page.pageNum,
          pageSize: this.page.pageSize
        }
        const response = await getPetList(params)
        if (response.code === 200 && response.data) {
          this.petList = response.data.list || []
          this.total = response.data.total || 0
        } else {
          this.$message.error('获取宠物列表失败：' + (response.message || '未知错误'))
        }
      } catch (error) {
        console.error('获取宠物列表失败:', error)
        this.$message.error('获取宠物列表失败：' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },
    // 搜索
    handleSearch() {
      this.page.pageNum = 1
      this.fetchPetList()
    },
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        name: '',
        category: '',
        adoptionStatus: ''
      }
      this.handleSearch()
    },
    // 查看详情
    viewDetail(id) {
      this.$router.push(`/main/pets/${id}`)
    },
    // 编辑宠物
    handleEdit(id) {
      this.$router.push(`/pets/${id}/edit`)
    },
    // 删除宠物
    handleDelete(pet) {
      if (pet.adoptionStatus === 'ADOPTED') {
        this.$message.warning('已被领养的宠物不能删除')
        return
      }
      this.$confirm('确认删除该宠物吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePet(pet.id).then(() => {
          this.$message.success('删除成功')
          this.fetchPetList()
        })
      }).catch(() => {})
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.page.pageSize = val
      this.fetchPetList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.fetchPetList()
    }
  },
  created() {
    this.fetchPetList()
  }
}
</script>

<style lang="scss" scoped>
.pet-list-container {
  .search-card {
    margin-bottom: 20px;
  }

  .operation-bar {
    margin-bottom: 20px;
  }

  .pet-card {
    margin-bottom: 20px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    }

    .pet-image {
      position: relative;
      height: 200px;
      overflow: hidden;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .adoption-status {
        position: absolute;
        top: 10px;
        right: 10px;
        padding: 2px 8px;
        border-radius: 4px;
        color: white;
        font-size: 12px;

        &.available {
          background-color: #67C23A;
        }

        &.adopted {
          background-color: #909399;
        }
      }
    }

    .pet-info {
      padding: 14px;

      .pet-name {
        margin: 0;
        font-size: 16px;
        color: #303133;
      }

      .pet-meta {
        margin: 8px 0;
        font-size: 13px;
        color: #909399;

        span {
          margin-right: 10px;
        }
      }

      .pet-actions {
        border-top: 1px solid #EBEEF5;
        padding-top: 10px;
        margin-top: 10px;
        text-align: right;

        .el-button {
          padding: 0 10px;
        }

        .danger {
          color: #F56C6C;
        }
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }

  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 30px;
  }
}
</style> 